package controller

import (
	"CartApp/models"
	"CartApp/pkg/util"
	"CartApp/serializer"
	"CartApp/service"
	"strconv"

	"github.com/gin-gonic/gin"
)

func CreatePostHandler(c *gin.Context) {
	p := new(models.CreatePost)
	if err := c.ShouldBindJSON(p); err != nil {
		c.JSON(400, ErrorResponse(err))
		util.Logger().Info(err)
		return
	}
	//获取当前用户
	chaim, _ := util.ParseToken(c.GetHeader("Authorization"))
	res := service.CreatePost(chaim.Id, p)
	c.JSON(200, res)
}

// 更新POST
func UpdatePostHandler(c *gin.Context) {
	p := new(models.Post)
	if err := c.ShouldBindJSON(p); err != nil {
		c.JSON(400, ErrorResponse(err))
		util.Logger().Info(err)
		return
	}
	res := service.UpdatePost(p)
	c.JSON(200, res)

}

// 获取post的内容 进行编辑处理
func GetPostHandler(c *gin.Context) {
	paramId := c.Param("id")
	id, err := strconv.ParseInt(paramId, 10, 64)
	if err != nil {
		c.JSON(400, ErrorResponse(err))
		util.Logger().Info(err)
		return
	}
	res := service.GetPost(id)
	c.JSON(200, res)
}

//post的列表查询
func PostListHandler(c *gin.Context) {
	p := new(models.Post)
	listPage := &serializer.ListPostService{
		Limit: 2,
		Size:  1,
	}
	chaim, _ := util.ParseToken(c.GetHeader("Authorization"))
	if err := c.ShouldBind(p); err != nil {
		c.JSON(400, ErrorResponse(err))
		util.Logger().Info(err)
		return
	}
	res := service.PostList(chaim.Id, listPage)
	c.JSON(200, res)
}

// 用户与列表之间的关系数据
func UserPostListHandler(c *gin.Context) {
	listPage := &serializer.ListPostService{
		Limit: 10,
		Size:  1,
	}
	res := service.UserPostList(listPage)
	c.JSON(200, res)
}
